package cn.tedu.v1;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

/**
 * 聊天室 Version 1.1
 * 服务器 功能：1.服务器申请端口号：软件具备端口号
 *            2.在start方法中：等待客户端连接，返回socket
 *                            IO流入
 *     【新增】3.所有服务器端异常，全部捕获，明确提示
 *           4.关闭serverSocket
 */
public class Server {
    private ServerSocket serverSocket;
    public Server() {
        try {
            serverSocket = new ServerSocket(7878);
            //BindException  端口号已经被占用
        } catch (BindException e){
            System.out.println("端口号已经被占用");
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    //3.创建start 方法accept()等待客户端的连接 传输数据：IO
    public void start() {
        //等待客户端连接，指定端口号：6666
        String str = null;
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        try {
            System.out.println("等待客户端连接");
            Socket socket = serverSocket.accept();//卡住--客户端连接---通过
            System.out.println("一个客户端连接上了");

            is = socket.getInputStream();
            isr = new InputStreamReader(is, "UTF8");
            br = new BufferedReader(isr);

            while (true) {
                str = br.readLine();
                //获取一行字符串，交给str保存
                System.out.println("客户端：" + str);//打印 客户端发来的文本
            }
        } catch(UnsupportedEncodingException e){
            System.out.println("请检查客户端/服务器端连接：不一致");
        } catch(SocketException e){
            System.out.println("客户端连接被重置");
        } catch (IOException e) {
            System.out.println("客户端连接失效");
        } finally {
            if (br != null)
                try {
                        br.close();
                    serverSocket.close();
                } catch (Exception e) {
                    System.out.println("读入流断开连接");
                }
            try {
                serverSocket.close();
            }catch(IOException e){
                System.out.println("客户端socket断开连接");
            }
        }
        }

    //4.创建主方法--服务器端启动
    public static void main(String[] args)  {
        Server server=new Server();
        server.start();
    }
}
